package com.tonann.app.conf;

import com.tonann.app.VO.MySensor;
import com.tonann.app.domain.AppDevice;
import com.tonann.app.domain.AppDeviceAdmin;
import com.tonann.app.domain.AppDeviceOperator;
import com.tonann.app.domain.AppSensor;
import com.tonann.app.mapper.AppDeviceAdminMapper;
import com.tonann.app.mapper.AppDeviceOperatorMapper;
import com.tonann.app.service.IAppDeviceService;
import com.tonann.app.service.IAppSensorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MySensorConf {

    @Resource
    private IAppDeviceService deviceService;
    @Resource
    private IAppSensorService sensorService;

    @Resource
    private AppDeviceAdminMapper appDeviceAdminMapper;

    @Resource
    private AppDeviceOperatorMapper appDeviceOperatorMapper;

    @Bean
    private void dataMap() {
        log.info("数据准备start");
        List<AppDeviceAdmin> adminList = appDeviceAdminMapper.selectAppDeviceAdminList(new AppDeviceAdmin());
        List<AppDeviceOperator> operatorList = appDeviceOperatorMapper.selectAppDeviceOperatorList(new AppDeviceOperator());
        List<Long> adminIds = adminList.stream().map(AppDeviceAdmin::getUserId).collect(Collectors.toList());
        List<Long> operatorIds = operatorList.stream().map(AppDeviceOperator::getUserId).collect(Collectors.toList());
        Set<Long> userSet = adminIds.stream().distinct().collect(Collectors.toSet());
        userSet.addAll(operatorIds.stream().distinct().collect(Collectors.toSet()));
        for (Long id : userSet) {
            List<AppDevice> deviceList = deviceService.selectDeviceListByUserId(id);
            MySensor.getInstance().userDeviceMap.put(id, deviceList);
            Map<String, List<AppDevice>> typeMap = deviceList.stream().collect(Collectors.groupingBy(AppDevice::getType));
            for (String type : typeMap.keySet()) {
                List<AppDevice> devices = typeMap.get(type);
                List<Long> deviceIds = devices.stream().map(AppDevice::getDeviceId).collect(Collectors.toList());
                if (!deviceIds.isEmpty()) {
                    String key = deviceIds.stream().map(Object::toString).collect(Collectors.joining(","));
                    List<AppSensor> sensorList = sensorService.selectAppSensorAllListByDeviceIdsForAPP(deviceIds);
                    MySensor.getInstance().devicesSensorMap.put(key, sensorList);
                }
            }
        }
        log.info("数据准备end");
    }
}
